package org.crystal.tradecraft.serialization;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import org.ta4j.core.Bar;
import org.ta4j.core.BaseBar;
import org.ta4j.core.num.DecimalNum;

import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;

public class BarDeserializer extends JsonDeserializer<Bar> {

    @Override
    public Bar deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
        JsonNode jsonNode = jsonParser.readValueAsTree();

        return BaseBar.builder()
            .timePeriod(Duration.ofMillis(jsonNode.get(6).asLong() - jsonNode.get(0).asLong()))
            .openPrice(DecimalNum.valueOf(jsonNode.get(1).asDouble()))
            .highPrice(DecimalNum.valueOf(jsonNode.get(2).asDouble()))
            .lowPrice(DecimalNum.valueOf(jsonNode.get(3).asDouble()))
            .closePrice(DecimalNum.valueOf(jsonNode.get(4).asDouble()))
            .volume(DecimalNum.valueOf(jsonNode.get(5).asDouble()))
            .endTime(Instant.ofEpochMilli(jsonNode.get(6).asLong()).atZone(ZoneOffset.UTC))
            .amount(DecimalNum.valueOf(jsonNode.get(7).asDouble()))
            .trades(jsonNode.get(8).asInt())
            .build();
    }
}